const { userController } = require("./api/controller/user_controller");
const { BaseResult } = require("./domain/base_result");
const { DB_ERROR, SERVER_ERROR } = require("./domain/constance")

let globalResponse = null


const requestHandle = async (req, res) => {

    let { url } = req;

    res.setHeader("Content-Type", "text/json;charset=utf-8")

    globalResponse = res;

    // 处理 post请求中的data数据
    // handlePostData(req)


    switch (true) {

        case url.startsWith("/login"):
            userController.login(req, res);
            break;

        case url.startsWith("/register"):
            userController.register(req, res)
            break;

        case url.startsWith("/list"):
            userController.list(req, res)
            break;

        case url.startsWith("/save"):
            userController.save(req, res)
            break;

        case url.startsWith("/delete"):
            userController.remove(req, res)
            break;

        default:
            res.writeHead(404, {
                "Content-Type": "text/html;charset=utf-8",
            });
            res.end()
            break;
    }
}

// 全局异常处理
process.on('unhandledRejection', function (err, _) {

    console.log("拦截到异常信息 : " + err)
    // 捕获服务器的内部错误 
    if (typeof err === 'string' && err.startsWith(DB_ERROR)) {
        globalResponse.end(BaseResult.notOk(SERVER_ERROR))
    }

})

module.exports = {
    requestHandle
}